<template>
  <div class="patrol-route-map">
    <div class="map-header">
      <div class="header-left">
        <el-button icon="el-icon-back" size="small" @click="goBack">返回</el-button>
        <h3>巡更路线地图</h3>
      </div>
      <div class="map-controls">
        <el-button size="small" type="primary" @click="calculateShortestPath">计算最短路线</el-button>
        <el-button size="small" @click="clearRoute">清除路线</el-button>
        <el-button size="small" type="success" @click="manualLoadData" :loading="loading">手动加载数据</el-button>
      </div>
    </div>
    <div class="amap-container" id="container"></div>
    <div class="point-list">
      <h4>巡更点列表 <span v-if="routeId">(路线ID: {{routeId}})</span></h4>
      <div v-if="localPatrolPoints.length === 0" class="empty-data">
        <p>暂无巡更点数据</p>
        <el-input v-model="manualRouteId" placeholder="请输入路线ID" style="width: 200px; margin-right: 10px;"></el-input>
        <el-button size="small" type="primary" @click="loadByManualId">加载数据</el-button>
      </div>
      <el-table v-else :data="localPatrolPoints" style="width: 100%" height="300">
        <el-table-column prop="name" label="巡更点名称"></el-table-column>
        <el-table-column label="坐标" width="180">
          <template slot-scope="scope">
            {{scope.row.longitude}}, {{scope.row.latitude}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="locatePoint(scope.row)" type="text" size="small">定位</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
  name: 'PatrolRouteMap',
  props: {
    routeId: {
      type: [Number, String],
      required: false,
      default: null,
      validator: function(value) {
        console.log('Props验证 - 接收到的routeId:', value, '类型:', typeof value);
        return true; // 允许任何值
      }
    },
    patrolPoints: {
      type: Array,
      default: () => []
    },
    // 是否自动从数据库加载巡更点
    autoLoad: {
      type: Boolean,
      default: true
    },
    // 小区ID，用于查询巡更点
    communityId: {
      type: [Number, String],
      default: null
    }
  },
  
  // 添加路由参数监听
  beforeRouteEnter(to, from, next) {
    next(vm => {
      console.log('beforeRouteEnter - 路由参数:', to.params);
      console.log('beforeRouteEnter - 查询参数:', to.query);
      
      // 尝试从路由参数或查询参数获取ID
      const id = to.params.id || to.query.id;
      if (id && !vm.routeId) {
        console.log('从路由获取到ID:', id);
        vm.routeId = id;
        vm.fetchPatrolPointsByRouteId();
      } else {
        console.log('未从路由获取到ID');
      }
    });
  },
  data() {
    return {
      map: null,
      markers: [],
      polyline: null,
      infoWindow: null,
      shortestPath: [],
      loading: false,
      center: { lng: 106.550483, lat: 29.563707 }, // 默认中心点（重庆）
      AMap: null,
      visitedPoints: new Set(),
      currentPath: [],
      mapKey: {
        key: 'b268e01f642b605bfbbc07868ae8ced4', // 高德地图key
        securityJsCode: '88e0ae02bde4aa10d42fcd36522c833b', // 安全密钥
      },
      localPatrolPoints: [], // 本地存储的巡更点数据
      fetchingData: false, // 是否正在获取数据
      manualRouteId: '' // 手动输入的路线ID
    }
  },
  created() {
    console.log('组件created - props routeId:', this.routeId);
    console.log('组件created - 路由参数:', this.$route?.params);
    console.log('组件created - 查询参数:', this.$route?.query);
    
    // 尝试从路由获取ID
    const routeId = this.getRouteIdFromRoute();
    if (routeId) {
      console.log('从路由获取到ID:', routeId);
      this.routeId = String(routeId); // 确保以字符串形式存储
    }
    
    // 在created阶段就开始获取数据
    if (this.routeId) {
      this.fetchPatrolPointsByRouteId();
    }
  },
  
  mounted() {
    console.log('组件mounted - props routeId:', this.routeId);
    this.initAMap();
    
    // 如果没有路由ID，尝试从localStorage获取
    if (!this.routeId) {
      const savedId = localStorage.getItem('lastPatrolRouteId');
      if (savedId) {
        console.log('从localStorage获取到ID:', savedId);
        this.routeId = String(savedId); // 确保以字符串形式存储
        this.fetchPatrolPointsByRouteId();
      }
    }
  },
  watch: {
    patrolPoints: {
      handler(newPoints) {
        console.log('patrolPoints变更:', newPoints?.length || 0);
        if (newPoints && newPoints.length > 0 && this.map) {
          this.localPatrolPoints = [...newPoints];
          this.loadPointsOnMap();
        }
      },
      deep: true
    },
    routeId: {
      handler(newId) {
        if (newId) {
          console.log('路线ID变更:', newId);
          // 保存到localStorage
          localStorage.setItem('lastPatrolRouteId', String(newId));
          this.fetchPatrolPointsByRouteId();
        }
      },
      immediate: true
    },
    '$route': {
      handler(newRoute) {
        console.log('路由变更:', newRoute.params, newRoute.query);
        const routeId = this.getRouteIdFromRoute();
        if (routeId && routeId !== this.routeId) {
          console.log('路由变更，获取到新ID:', routeId);
          this.routeId = routeId; // 确保以字符串形式存储
           this.fetchPatrolPointsByRouteId(); 
        }
      },
      deep: true
    }
  },
  methods: {
    // 从路由获取ID
    getRouteIdFromRoute() {
      if (!this.$route) return null;
      // 确保以字符串形式返回ID，避免大数值精度丢失
      const id = this.$route.params.id || this.$route.query.id || this.$route.query.routeId || null;
      return id ? String(id) : null;
    },
    
    // 手动加载数据
    manualLoadData() {
      if (this.routeId) {
        this.fetchPatrolPointsByRouteId();
      } else {
        this.$message.warning('请先设置路线ID');
      }
    },
    
    // 根据手动输入的ID加载数据
    loadByManualId() {
      if (!this.manualRouteId) {
        this.$message.warning('请输入路线ID');
        return;
      }
      
      this.routeId = String(this.manualRouteId); // 确保以字符串形式存储
      this.fetchPatrolPointsByRouteId();
    },
    
    // 初始化高德地图
    initAMap() {
      // 设置安全密钥
      window._AMapSecurityConfig = {
        securityJsCode: this.mapKey.securityJsCode,
      }
      
      // 加载高德地图API
      AMapLoader.load({
        key: this.mapKey.key,
        version: '2.0',
        plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.DragRoute'],
      }).then((AMap) => {
        this.AMap = AMap;
        
        // 创建地图实例
        this.map = new AMap.Map('container', {
          viewMode: '2D',
          zoom: 13,
          center: [this.center.lng, this.center.lat],
        });
        
        // 添加控件
        this.map.addControl(new AMap.Scale());
        this.map.addControl(new AMap.ToolBar());
        
        // 创建信息窗体
        this.infoWindow = new AMap.InfoWindow({
          offset: new AMap.Pixel(0, -30),
          closeWhenClickMap: true
        });
        
        // 如果有巡更点数据，加载到地图上
        if (this.localPatrolPoints.length > 0) {
          this.loadPointsOnMap();
        } else if (this.patrolPoints && this.patrolPoints.length > 0) {
          this.localPatrolPoints = [...this.patrolPoints];
          this.loadPointsOnMap();
        }
        
        console.log('地图初始化完成');
      }).catch(e => {
        console.error('高德地图加载失败', e);
        this.$message.error('地图加载失败，请刷新重试');
      });
    },
    
    // 从后端获取巡更路线关联的巡更点数据
    fetchPatrolPointsByRouteId() {
      if (!this.routeId || this.fetchingData) return;
      
      console.log('开始获取巡更路线详情, ID:', this.routeId, '类型:', typeof this.routeId);
      
      // 确保ID是字符串类型
      const routeIdStr = String(this.routeId);
      console.log('转换后的ID:', routeIdStr);
      
      this.fetchingData = true;
      this.loading = true;
      
      // 获取巡更路线详情，包含关联的巡更点ID
      const url = `api/patrol-server/patrolRoute/getById/${routeIdStr}`;
      console.log('API请求URL:', url);
      
      this.$axios.get(url)
        .then(response => {
          console.log('巡更路线详情响应:', response.data);
          if (response.data && response.data.code === 200) {
            const routeData = response.data.data;
            console.log('巡更路线数据:', routeData);
            
            // 检查巡更点ID的不同可能字段名
            let pointIds = [];
            if (Array.isArray(routeData.patrolPoints)) {
              pointIds = routeData.patrolPoints.map(id => String(id)); // 转为字符串避免精度丢失
              console.log('从patrolPoints字段获取到巡更点IDs');
            } else if (Array.isArray(routeData.points)) {
              pointIds = routeData.points.map(id => String(id));
              console.log('从points字段获取到巡更点IDs');
            } else if (Array.isArray(routeData.pointIds)) {
              pointIds = routeData.pointIds.map(id => String(id));
              console.log('从pointIds字段获取到巡更点IDs');
            } else if (routeData.patrolPointIds && typeof routeData.patrolPointIds === 'string') {
              // 如果是字符串形式的ID列表，尝试解析
              try {
                const parsed = JSON.parse(routeData.patrolPointIds);
                pointIds = Array.isArray(parsed) ? parsed.map(id => String(id)) : [];
                console.log('从patrolPointIds字符串解析获取到巡更点IDs');
              } catch (e) {
                console.error('解析patrolPointIds字符串失败:', e);
                pointIds = routeData.patrolPointIds.split(',').map(id => id.trim());
                console.log('尝试通过分隔符解析patrolPointIds');
              }
            }
            
            console.log('解析后的巡更点IDs:', pointIds);
            
            if (!pointIds || pointIds.length === 0) {
              this.$message.warning('该巡更路线没有关联的巡更点');
              this.loading = false;
              this.fetchingData = false;
              return;
            }
            
            // 获取所有巡更点详情
            this.fetchPatrolPointDetails(pointIds);
          } else {
            this.$message.error(response.data?.message || '获取巡更路线详情失败');
            this.loading = false;
            this.fetchingData = false;
          }
        })
        .catch(error => {
          console.error('获取巡更路线详情错误:', error);
          this.$message.error('获取巡更路线详情失败');
          this.loading = false;
          this.fetchingData = false;
        });
    },
    
    // 获取巡更点详情
    fetchPatrolPointDetails(pointIds) {
      if (!pointIds || pointIds.length === 0) {
        this.loading = false;
        this.fetchingData = false;
        return;
      }
      
      console.log('开始获取巡更点详情, IDs:', pointIds);
      
      // 这里需要根据实际API调整，假设有一个批量查询巡更点的接口
      const promises = pointIds.map(id => {
        // 确保ID作为字符串使用，避免大数值精度丢失
        const pointId = String(id);
        console.log(`正在请求巡更点ID: ${pointId}的详情`);
        return this.$axios.get(`api/patrol-server/patrol/queryById/${pointId}`);
      });
      
      Promise.all(promises)
        .then(responses => {
          console.log('巡更点详情响应数量:', responses.length);
          responses.forEach((res, index) => {
            console.log(`第${index+1}个响应:`, res.data);
          });
          
          const validPoints = responses
            .filter(res => {
              const isValid = res.data && res.data.code === 200;
              if (!isValid) {
                console.warn('发现无效响应:', res.data);
              }
              return isValid;
            })
            .map(res => {
              const point = res.data.data;
              console.log('处理巡更点数据:', point);
              // 检查所有可能的坐标字段
              const longitude = point.longitude || point.lon || point.lng;
              const latitude = point.latitude || point.lat;
              
              console.log(`巡更点坐标提取: ID=${point.pointId}, 名称=${point.pointName}, 经度=${longitude}, 纬度=${latitude}`);
              
              return {
                id: point.pointId,
                name: point.pointName,
                longitude: longitude,
                latitude: latitude
              };
            })
            .filter(point => {
              const hasCoords = point.longitude && point.latitude;
              if (!hasCoords) {
                console.warn('巡更点缺少有效坐标:', point);
              }
              return hasCoords;
            });
            
          console.log('有效的巡更点数据:', validPoints);
          
          if (validPoints.length === 0) {
            this.$message.warning('未找到有效的巡更点坐标');
          } else {
            this.localPatrolPoints = validPoints;
            if (this.map) {
              this.loadPointsOnMap();
            } else {
              console.error('地图尚未初始化，无法加载巡更点');
            }
          }
        })
        .catch(error => {
          console.error('获取巡更点详情错误:', error);
          this.$message.error('获取巡更点详情失败');
        })
        .finally(() => {
          this.loading = false;
          this.fetchingData = false;
        });
    },
    
    // 加载巡更点到地图上
    loadPointsOnMap() {
      if (!this.map || !this.AMap) {
        console.error('地图未初始化');
        return;
      }
      
      // 清除现有标记
      this.clearMarkers();
      
      const pointsToUse = this.localPatrolPoints.length > 0 ? this.localPatrolPoints : this.patrolPoints;
      
      if (!pointsToUse || pointsToUse.length === 0) {
        console.log('没有可用的巡更点数据');
        return;
      }
      
      console.log('开始加载巡更点到地图, 数量:', pointsToUse.length);
      console.log('巡更点数据详情:', JSON.stringify(pointsToUse));
      
      // 创建坐标点集合
      const points = [];
      
      // 添加每个巡更点的标记
      pointsToUse.forEach((point, index) => {
        if (!point.longitude || !point.latitude) {
          console.warn(`巡更点 ${index} 缺少坐标:`, point);
          return;
        }
        
        try {
          const longitude = parseFloat(point.longitude);
          const latitude = parseFloat(point.latitude);
          
          if (isNaN(longitude) || isNaN(latitude)) {
            console.warn(`巡更点 ${index} 坐标格式无效:`, point);
            return;
          }
          
          const position = [longitude, latitude];
          points.push(position);
          
          console.log(`添加标记 ${index + 1}: ${point.name}, 位置:`, position);
          
          // 创建标记
          const marker = new this.AMap.Marker({
            position: position,
            title: point.name,
            label: {
              content: `${index + 1}. ${point.name}`,
              direction: 'right',
              offset: new this.AMap.Pixel(10, 0)
            }
          });
          
          // 添加点击事件
          marker.on('click', () => {
            this.infoWindow.setContent(`
              <div style="padding: 8px;">
                <h4 style="margin: 0 0 5px 0;">${point.name}</h4>
                <p style="margin: 0;">位置: ${point.longitude}, ${point.latitude}</p>
              </div>
            `);
            this.infoWindow.open(this.map, position);
          });
          
          this.map.add(marker);
          this.markers.push(marker);
        } catch (error) {
          console.error(`添加巡更点标记 ${index} 失败:`, error);
        }
      });
      
      // 调整地图视野以包含所有标记
      if (points.length > 0) {
        console.log('调整地图视野，标记数量:', this.markers.length);
        this.map.setFitView(this.markers);
      } else {
        console.warn('没有有效的标记点，无法调整地图视野');
      }
    },
    
    // 清除所有标记
    clearMarkers() {
      if (this.markers.length > 0) {
        this.map.remove(this.markers);
        this.markers = [];
      }
    },
    
    // 清除路线
    clearRoute() {
      if (this.polyline) {
        this.map.remove(this.polyline);
        this.polyline = null;
      }
      this.shortestPath = [];
      this.visitedPoints.clear();
      this.currentPath = [];
    },
    
    // 定位到特定巡更点
    locatePoint(point) {
      if (!point.longitude || !point.latitude) {
        this.$message.warning('该巡更点没有有效的坐标信息');
        return;
      }
      
      const position = [parseFloat(point.longitude), parseFloat(point.latitude)];
      this.map.setCenter(position);
      this.map.setZoom(18);
      
      // 显示信息窗口
      this.infoWindow.setContent(`
        <div style="padding: 8px;">
          <h4 style="margin: 0 0 5px 0;">${point.name}</h4>
          <p style="margin: 0;">位置: ${point.longitude}, ${point.latitude}</p>
        </div>
      `);
      this.infoWindow.open(this.map, position);
    },
    
    // 计算最短路径 (使用贪心算法)
    calculateShortestPath() {
      const pointsToUse = this.localPatrolPoints.length > 0 ? this.localPatrolPoints : this.patrolPoints;
      
      if (!pointsToUse || pointsToUse.length < 2) {
        this.$message.warning('至少需要两个巡更点才能计算路线');
        return;
      }
      
      this.loading = true;
      this.clearRoute();
      
      // 过滤掉没有坐标的点
      const validPoints = pointsToUse.filter(p => p.longitude && p.latitude);
      
      if (validPoints.length < 2) {
        this.$message.warning('至少需要两个有效坐标的巡更点');
        this.loading = false;
        return;
      }
      
      // 使用贪心算法计算最短路径（最近邻算法）
      const path = this.calculateNearestNeighborPath(validPoints);
      
      // 绘制路线
      this.drawPath(path);
      this.loading = false;
    },
    
    // 最近邻算法计算路径
    calculateNearestNeighborPath(points) {
      // 从第一个点开始
      const path = [points[0]];
      const unvisited = [...points.slice(1)];
      
      let currentPoint = path[0];
      
      // 循环直到所有点都被访问
      while (unvisited.length > 0) {
        // 找到距离当前点最近的点
        let minDistance = Infinity;
        let nearestIndex = -1;
        
        unvisited.forEach((point, index) => {
          const distance = this.calculateDistance(
            currentPoint.latitude, currentPoint.longitude,
            point.latitude, point.longitude
          );
          
          if (distance < minDistance) {
            minDistance = distance;
            nearestIndex = index;
          }
        });
        
        // 添加最近的点到路径
        currentPoint = unvisited[nearestIndex];
        path.push(currentPoint);
        unvisited.splice(nearestIndex, 1);
      }
      
      return path;
    },
    
    // 计算两点之间的距离（使用Haversine公式）
    calculateDistance(lat1, lon1, lat2, lon2) {
      const R = 6371; // 地球半径（公里）
      const dLat = this.deg2rad(lat2 - lat1);
      const dLon = this.deg2rad(lon2 - lon1);
      const a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2); //
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
      const distance = R * c;
      return distance;
    },
    
    // 角度转弧度
    deg2rad(deg) {
      return deg * (Math.PI/180);
    },
    
    // 绘制路径
    drawPath(path) {
      if (!path || path.length < 2) return;
      
      // 创建坐标点数组
      const points = path.map(p => [parseFloat(p.longitude), parseFloat(p.latitude)]);
      
      // 创建折线对象
      this.polyline = new this.AMap.Polyline({
        path: points,
        strokeColor: "#3388ff",
        strokeWeight: 6,
        strokeOpacity: 0.8,
        strokeStyle: "solid",
        strokeDasharray: [10, 5],
        lineJoin: 'round',
        lineCap: 'round',
        zIndex: 50,
      });
      
      // 将折线添加到地图
      this.map.add(this.polyline);
      
      // 保存最短路径
      this.shortestPath = path;
      
      // 通知父组件
      this.$emit('path-calculated', path);
      
      // 调整地图视野以包含整个路线
      this.map.setFitView([this.polyline]);
    },
    goBack(){
        this.$router.go(-1);
    }
  }
}
</script>

<style scoped>
.patrol-route-map {
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.map-header {
  padding: 10px 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.map-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.amap-container {
  height: 400px;
  width: 100%;
}

.point-list {
  padding: 10px 15px;
  border-top: 1px solid #ebeef5;
  flex: 1;
  overflow: auto;
}

.point-list h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  font-weight: 500;
}

.map-controls {
  display: flex;
  gap: 10px;
}

.empty-data {
  text-align: center;
  padding: 20px;
  color: #909399;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.empty-data p {
  margin-bottom: 10px;
}
</style>